import os
import chardet

def convert_to_utf8(file_path):
    """将文件转换为UTF-8编码，并确保中文字符正确处理"""
    try:
        # 检测文件原始编码
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            original_encoding = result['encoding']
        
        # 如果无法检测到编码，使用默认编码（如 gbk）
        if not original_encoding:
            print(f"无法检测文件 {file_path} 的编码，使用默认编码 gbk")
            original_encoding = 'utf-8'
        
        # 如果已经是UTF-8则跳过
        if original_encoding.lower() == 'utf-8':
            print(f"文件 {file_path} 已经是UTF-8编码，跳过转换")
            return
        
        # 读取文件内容并转换为UTF-8
        with open(file_path, 'r', encoding=original_encoding, errors='ignore') as f:
            content = f.read()
        
        # 以UTF-8写入文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"成功转换 {file_path} 为UTF-8编码")
    
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {str(e)}")

def process_directory(directory):
    """递归处理目录中的所有.c和.h文件"""
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(('.c', '.h')):
                file_path = os.path.join(root, file)
                convert_to_utf8(file_path)

if __name__ == "__main__":
    current_dir = os.getcwd()  # 获取当前工作目录
    print(f"开始处理目录: {current_dir}")
    process_directory(current_dir)
    print("转换完成")